import 'package:dio/dio.dart';
import 'package:fsharing/core/models/store_categories.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class StoreCategoriesModel extends ViewModel {
  final Api api;
  final int storeId;
  final int parentCategoryId;
  final int layerLevel;
  String _errorMessage;
  StoreCategories _storeCategories;

  StoreCategoriesModel(this.api, this.storeId, this.parentCategoryId, this.layerLevel) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  StoreCategories get storeCategories => _storeCategories;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _storeCategories = await api.storeCategories(
        storeId,
        parentCategoryId,
        layerLevel,
        cancelToken,
      );
      final list = _storeCategories.childCategoriesV2.first?.children ?? [];
      if (list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
